<template>
  <view class="upload">
    <u-upload
      :fileList="fileListImages"
      @afterRead="afterRead"
      @delete="deletePic"
      multiple
      :maxCount="1"
      :width="uploadWidth"
      :height="uploadHeight"
    >
      <slot></slot>
    </u-upload>
  </view>
</template>
<script>
export default {
  props: {
    uploadWidth: {
      type: String,
      default: "192rpx",
    },
    uploadHeight: {
      type: String,
      default: "192rpx",
    },
    fileList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      fileListImages: [],
    };
  },
  onLoad: function (option) {
    console.log(11111);
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this.fileListImages.splice(event.index, 1);
      this.$emit("getUpLoadImage", this.fileListImages);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this.fileListImages.length;
      lists.map((item) => {
        this.fileListImages.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const res = await this.uploadFilePromise(lists[i].url);
        if (res.code == 0) {
          let item = this.fileListImages[fileListLen];
          this.fileListImages.splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: "success",
              message: "上传成功",
              url: res.data.url,
              id: res.data.id,
            })
          );
          fileListLen++;
        } else if (res.code == 1000) {
          wx.showToast({
            title: res.message,
            icon: "none",
            duration: 2000,
            mask: false,
            success: function () {
              setTimeout(() => {
                uni.navigateTo({
                  url: "/pages/login/index",
                });
              }, 2000);
            },
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
            duration: 2000,
          });
        }
      }
      this.$emit("getUpLoadImage", this.fileListImages);
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: "/up_load_api/attach/upload",
          header: {
            Authorization: uni.getStorageSync("token"),
          },
          filePath: url,
          success: (res) => {
            resolve(JSON.parse(res.data));
          },
          fail: (error) => {
            console.log("error", errow);
            reject(error);
          },
        });
      });
    },
  },
  watch: {
    fileList: {
      handler(newVal, oldVal) {
        this.fileListImages = newVal;
      },
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
</style>